<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { useDataStore } from '../stores/userDataStore'
import { getUserData, postLog } from '../script/getUserData'
//import { useRouter } from 'vue-router'
import { send } from '@/script/ws.js'
import { gameStores } from '../stores/gameStores'
import { check } from '../script/check'
import { openWS } from '@/script/ws.js'


const WebSocketType = {
    Error: 0, //错误
    GroupList: 1,
    GroupChat: 2,
    SingleChat: 3
}
const leve = ref(false)
const gameStore = gameStores()
//const router = useRouter()
const CategoryStore = useDataStore()

const style1 = ref({})
const style2 = ref({})

const goback = () => {
    if (gameStore.win === 0) {
        leve.value = true
    } else {
        gameStore.InGame = false
        window.location.href = '/hall'
    }

}

const notGoBack = () => {
    leve.value = false
}

const leveSuer = () => {
    gameStore.InGame = false
    const enemyInf = {
        type: "lose",
        inf: {}
    }
    gameStore.win = 2
    send(WebSocketType.SingleChat, JSON.stringify(enemyInf), CategoryStore.enemyInf.username)
    postLog(CategoryStore.enemyInf.id, 2)
    window.location.href = '/hall'
}
//倒计时

const time = ref()
time.value = gameStore.time
const timer = setInterval(() => {
    if (gameStore.win != 0) return
    if (time.value > 0) {
        time.value--; // 每次递减1秒
        gameStore.time = time.value
    } else {
        if (gameStore.isMe) {
            const enemyInf = {
                type: "lose",
                inf: {}
            }
            send(WebSocketType.SingleChat, JSON.stringify(enemyInf), CategoryStore.enemyInf.username)
            gameStore.win = 2
            postLog(CategoryStore.enemyInf.id, 2)
        } else {
            gameStore.win = 1
            
        }
        clearInterval(timer); // 当倒计时结束时清除定时器
    }
}, 1000); // 每隔1秒执行一次




const canvas1 = ref()
let context = null

const draw = (i, j) => {
    context.beginPath();
    if (gameStore.isMe) {
        context.fillStyle = "black";
        style2.value = {
            height: '0px'
        }
        style1.value = {
            height: '100px'
        }
    } else {
        context.fillStyle = "white";
        setCircles((j / 36) - 1, (i / 36) - 1, 2)
        style2.value = {
            height: '100px'
        }
        style1.value = {
            height: '0px'
        }
    }
    context.arc(i, j, 17, 0, 2 * Math.PI);//画圆
    context.fill();//填充
    //更新时间
    time.value = 60
    gameStore.time = time.value

    const res = check(circles, (j / 36) - 1, (i / 36) - 1, gameStore.isMe)
    if (res === 1) {
        gameStore.win = 1
        postLog(CategoryStore.enemyInf.id, 1)
    } else if (res === 2) {
        gameStore.win = 2
        postLog(CategoryStore.enemyInf.id, 2)
    }

    gameStore.isMe = !gameStore.isMe
}



watch(() => gameStore.enemyDraw, () => {
    draw(gameStore.enemyDraw.x, gameStore.enemyDraw.y)
})

//使用组存棋子的数组
let circles = [];
for (let i = 0; i < 19; i++) {
    circles[i] = [];
    for (let j = 0; j < 19; j++) {
        circles[i][j] = 0;
    }
}

//把对应的棋子放到数组里
//1 是自己的 永远是黑色
//2 是对方的 永远是白色
const setCircles = (i, j, value) => {
    circles[i][j] = value
    gameStore.gameData = circles
    //console.log(gameStore.gameData);
}

watch(canvas1, () => {
    //720 * 720
    //36*36为一个格子  24*24个格子 
    canvas1.value.addEventListener('click', (e) => {
        if (!gameStore.isMe) return
        if (gameStore.win !== 0) return
        let x = e.offsetX;
        let y = e.offsetY;
        if (x < 19 || x > 701 || y < 19 || y > 701) return;
        let ii = Math.floor((x + 18) / 36)
        let jj = Math.floor((y + 18) / 36)
        if (circles[jj - 1][ii - 1] !== 0) {
            return
        }
        let i = ii * 36;
        let j = jj * 36;
        setCircles(jj - 1, ii - 1, 1)

        draw(i, j)

        const enemyInf = {
            type: "draw",
            inf: {
                x: i,
                y: j
            }
        }
        send(WebSocketType.SingleChat, JSON.stringify(enemyInf), CategoryStore.enemyInf.username)

    })
});


const initCanvas = () => {
    canvas1.value.width = 720;
    canvas1.value.height = 720;
    context = canvas1.value.getContext("2d");
    for (let i = 1; i < 20; i++) {
        context.moveTo(36, 36 * i);
        context.lineTo(684, 36 * i);
        context.moveTo(36 * i, 36);
        context.lineTo(36 * i, 684);
        context.stroke()
    }
    if (gameStore.isMe) {
        style2.value = {
            height: '100px'
        }
    } else {
        style1.value = {
            height: '100px'
        }
    }
}

//刷新后恢复下完的棋子
const drawBack = () => {
    for (let i = 0; i < 19; i++) {
        for (let j = 0; j < 19; j++) {
            if (circles[i][j] === 1) {
                context.beginPath();
                context.fillStyle = "black";
                context.arc((j + 1) * 36, (i + 1) * 36, 17, 0, 2 * Math.PI);//画圆
                context.fill();//填充
            } else if (circles[i][j] === 2) {
                context.beginPath();
                context.fillStyle = "white";
                context.arc((j + 1) * 36, (i + 1) * 36, 17, 0, 2 * Math.PI);//画圆
                context.fill();//填充
            }
        }
    }
}



onMounted(() => {
    initCanvas()
    getUserData()
    if (!CategoryStore.getWS) {
        openWS()
        CategoryStore.getWS = true
        circles = [...gameStore.gameData]
        if (circles.length === 0) {
            for (let i = 0; i < 19; i++) {
                circles[i] = [];
                for (let j = 0; j < 19; j++) {
                    circles[i][j] = 0;
                }
            }
        }
        drawBack()
    }
})


onUnmounted(() => {
    clearInterval(timer);
})


</script>

<template>
    <div class="right-from-bracket" @click="goback()"><i class="fa-solid fa-right-from-bracket"></i></div>
    <div class="chessboard">
        <canvas ref="canvas1" class="canvas1"></canvas>
        <div class="timeBox">
            <i class="fa-solid fa-hourglass-half time-icon"></i>
            <div class="time">倒计时:{{ gameStore.time }}</div>
        </div>
        <div class="enemy">
            <div class="turnBoxforEn" :style="style1"><span class="turnBox">敌方回合</span></div>
            <img class="enemy-img" :src="CategoryStore.enemyInf.cover" alt="">
            <div class="enemy-name">{{ CategoryStore.enemyInf.username }}</div>
            <div class="enemy-win">胜场：{{ CategoryStore.enemyInf.winTime }}</div>
        </div>
        <div class="mine">
            <div class="turnBoxforMe" :style="style2"><span class="turnBox">我方回合</span></div>
            <img class="enemy-img" :src="CategoryStore.userData.imgSrc" alt="">
            <div class="enemy-name">{{ CategoryStore.userData.username }}</div>
            <div class="enemy-win">胜场：{{ CategoryStore.userData.winTime }}</div>
        </div>
    </div>

    <div class="sureBox" v-if="leve">
        <span>确认离开吗？</span>
        <div class="sureBox1" @click="leveSuer()">确定</div>
        <div class="sureBox2" @click="notGoBack()">取消</div>
    </div>
    <div class="winbox" v-if="gameStore.win === 1">
        <span style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">胜利</span>
    </div>

    <div class="winbox" v-if="gameStore.win === 2">
        <span style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">失败</span>
    </div>
</template>

<style scoped>
.chessboard {
    position: fixed;
    width: 720px;
    height: 720px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid rgba(210, 180, 90, 0.3);
    background: linear-gradient(180deg, #fffdf7 0%, #fdf6e3 100%);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    border-radius: 8px;
}

.canvas1 {
    top: 0;
    left: 0;
    width: 720px;
    height: 720px;
}

.enemy, .mine {
    position: fixed;
    width: 270px;
    height: 100px;
    background: rgba(255, 248, 220, 0.85);
    border: 1px solid rgba(210, 180, 90, 0.3);
    border-radius: 15px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}

.enemy {
    top: 0px;
    left: -280px;
}

.mine {
    bottom: 0px;
    right: -280px;
}

.enemy-name, .enemy-win {
    color: #5b4636;
}

.turnBoxforMe, .turnBoxforEn {
    background: rgba(210, 180, 90, 0.8);
}

.timeBox {
    position: fixed;
    height: 50px;
    width: 250px;
    top: 10px;
    right: -250px;
    background: rgba(255, 248, 220, 0.85);
    border: 1px solid rgba(210, 180, 90, 0.3);
    border-radius: 25px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    padding-left: 12px;
}

.time, .time-icon {
    color: #5b4636;
}

.sureBox {
    background: rgba(255, 248, 220, 0.95);
    border: 1px solid rgba(210, 180, 90, 0.3);
    border-radius: 15px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.sureBox1 {
    background: rgba(210, 180, 90, 0.85);
    color: #fff;
}

.sureBox2 {
    background: #ccc;
    color: #333;
}

.winbox {
    background: rgba(255, 248, 220, 0.95);
    border: 1px solid rgba(210, 180, 90, 0.3);
    border-radius: 15px;
    color: #5b4636;
    font-weight: bold;
}
</style>